package com.better517na.elasticseach.handlers;

import com.alibaba.fastjson.JSONObject;
import com.better517na.elasticseach.elasticsearch.Index;
import com.better517na.elasticseach.elasticsearch.client.ESHttpClient;
import com.better517na.elasticseach.utils.ESUtils;
import com.better517na.elasticseach.utils.StringUtil;


import java.text.MessageFormat;
import java.util.Map;

public class ExportDataHandler extends AbstractHandler implements Handler {

    private static final String META_DATA_TEMPLATE = "'{'\"index\":'{'\"_index\":\"{0}\",\"_type\":\"{1}\",\"_id\":\"{2}\"'}}'";

    public void doWork() {
        ESHttpClient producer = new ESHttpClient(context.getEsHost(), context.getEsPort());

        Index index = context.getProducer();
        boolean producerStatus = producer.indexStatus(index);

        if (!producerStatus){
            throw new RuntimeException("未获取到索引信息");
        }

        String scollID = getScollID(producer, index);

        if (!StringUtil.isNotEmpty(scollID)){
            System.out.println("游标获取失败");
            return;
        }

        index.setAction("_search/scroll");
        index.setType("");
        index.setIndex("");
        String scollTemplate = "'{'\"scroll\":\"10m\",\"scroll_id\":\"{0}\"'}'";
        int fileIndex = 0;
        int from = 0;

        System.out.println("开始导出文件");
        while(true){
            try {
                String queryBody = getQueryBody(scollTemplate, scollID);
                String result = producer.post(index, queryBody);
                Map<String, String> _docs = ESUtils.getHitsWithID(result);
                if (_docs.size() < 200){
                    break;
                }
                from +=200;

                if (from % context.getDocCount() == 0){
                    fileIndex++;
                }
                exportData(constructContent(_docs,META_DATA_TEMPLATE), fileIndex);
                System.out.println("导出到第" + fileIndex + "个文件");
            } catch (Exception e) {
                from += 200;
                e.printStackTrace();
            }
        }
    }

    public String getQueryBody(String queryDsl, String... param){
        String queryBody = MessageFormat.format(queryDsl,param);
        return queryBody;
    }

    private String getScollID(ESHttpClient client, Index index){
        String queryTemplate = "{\"query\":{\"bool\":{\"must\":[{\"match_all\":{}}],\"must_not\":[],\"should\":[]}},\"size\":200}";
        index.setAction("_search?scroll=10m");
        String post = client.post(index, queryTemplate);
        JSONObject scollRet = JSONObject.parseObject(post);

        return scollRet.getString("_scroll_id");
    }
}
